package sms

import (
	"cgs-server/server"
	"cgs-server/server/model"
	"go.mongodb.org/mongo-driver/bson"
	"time"
)

// 短信验证码
type Sms struct {
	PhoneNumber string `json:"phoneNumber" bson:"phoneNumber"`
	Code string `json:"code" bson:"code"`
	ExpireTime time.Time `json:"expireTime" bson:"expireTime"`
}

func (s *Sms) IsExpired() bool {
	return time.Now().After(s.ExpireTime)
}

// 存储验证码
func SaveSmsCode(data *Sms) error {
	// SmsValidationCode
	//sms := Sms{
	//	PhoneNumber: data["phoneNumber"].(string),
	//	Code: data["code"].(string),
	//	ExpireTime:  time.Now().Add(time.Minute * 5),
	//}

	data.ExpireTime = time.Now().Add(time.Minute * 5)

	db, err := server.Mongo()
	if err != nil {
		return err
	}
	_, err = db.InsertOne(server.SmsValidationCode, data)
	return err
}

// 根据手机号删除验证码
func DeleteSmsCode(phoneNumber string) error {
	db, err := server.Mongo()
	if err != nil {
		return err
	}
	filter := bson.M{
		"phoneNumber": phoneNumber,
	}
	_, err = db.DeleteMany(server.SmsValidationCode, filter)
	return err
}

// 获取验证码
func GetSmsCode(phoneNumber string) (*Sms, error) {
	db, err := server.Mongo()
	if err != nil {
		return nil, err
	}
	filter := bson.M{
		"phoneNumber": phoneNumber,
	}
	result := &Sms{}
	find, err := db.FindOne(server.SmsValidationCode, filter, result)
	if err != nil {
		return nil, err
	}
	if !find {
		return nil, model.NotFoundError("sms code")
	}
	return result, nil
}

// 更新验证码
func UpdateSmsCode(sms *Sms) error {
	err := DeleteSmsCode(sms.PhoneNumber)
	if err != nil {
		return err
	}

	return SaveSmsCode(sms)
}
